#include "StringEncoding.h"
#include <vector>

#include <Windows.h>

std::wstring StringEncoding::toUTF16(const std::string& src, Encoding from) {
	int len = MultiByteToWideChar((UINT)from, 0, src.c_str(), -1, NULL, 0);
	if (len > 0) {
		std::vector<wchar_t> buf(len);
		MultiByteToWideChar((UINT)from, 0, src.c_str(), -1, buf.data(), len);
		return std::wstring(buf.data());
	}
	return std::wstring();
}

std::string StringEncoding::fromUTF16(const std::wstring& src, Encoding to) {
	int len = WideCharToMultiByte((UINT)to, 0, src.c_str(), -1, NULL, 0, NULL, NULL);
	if (len > 0) {
		std::vector<char> buf(len);
		WideCharToMultiByte((UINT)to, 0, src.c_str(), -1, buf.data(), len, NULL, NULL);
		return std::string(buf.data());
	}
	return std::string();
}

std::string StringEncoding::convert(const std::string& src, Encoding from, Encoding to) {
	if (from == to) return src;
	int len = MultiByteToWideChar((UINT)from, 0, src.c_str(), -1, NULL, 0);
	if (len > 0) {
		std::vector<wchar_t> buf(len);
		MultiByteToWideChar((UINT)from, 0, src.c_str(), -1, buf.data(), len);
		int len2 = WideCharToMultiByte((UINT)to, 0, buf.data(), len, NULL, 0, NULL, NULL);
		if (len2 > 0) {
			std::vector<char> buf2(len2);
			WideCharToMultiByte((UINT)to, 0, buf.data(), len, buf2.data(), len2, NULL, NULL);
			return std::string(buf2.data());
		}
	}
	return std::string();
}
